package com.market.member.service.login;

import cn.hutool.core.util.ObjectUtil;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.model.dto.LoginReqDTO;
import com.block.common.service.IMemberCommonService;
import com.block.common.util.SmsCodeUtil;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.MemberInfo;
import com.block.db.mapper.MemberInfoMapper;
import com.market.member.model.dto.LoginResultDTO;
import com.market.member.service.ILoginTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
public class MobileLoginServiceImpl extends ILoginTypeService {

    @Autowired
    SmsCodeUtil smsCodeUtil;
    @Resource
    MemberInfoMapper memberInfoMapper;
    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ResponseVo toLogin(LoginReqDTO loginReqDTO) {

        String mobile = loginReqDTO.getMobile();

        MemberInfo memberInfo = memberInfoMapper.getBaseUserInfoByPhoneLock(mobile);

        boolean isNewMember = false;
        if (memberInfo == null){
            memberInfo = memberCommonService.saveRegisterMemberInfo(loginReqDTO.getClientType(), mobile, loginReqDTO.getRegisterChannel(),
                    loginReqDTO.getAppInfo(), loginReqDTO.getReqIp(), null, loginReqDTO.getZhima());
            if (ObjectUtil.isEmpty(memberInfo)){
                log.error("【手机号直接登陆】创建用户失败");
                return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "登录失败，请重试","");
            }
            isNewMember = true;
        }else{
            MemberInfo updateMember = new MemberInfo();
            updateMember.setUid(memberInfo.getUid());
            updateMember.setZhima(loginReqDTO.getZhima());
            memberInfoMapper.updateById(updateMember);
        }

        //
        LoginResultDTO loginResultDTO = new LoginResultDTO();
        loginResultDTO.setUid(memberInfo.getUid());
        loginResultDTO.setNewMember(isNewMember);
        loginResultDTO.setMemberType(memberInfo.getType());

        return new ResponseVo(AppRspCodeConstant.SUCCESS, loginResultDTO);
    }
}
